import { ref, onUnmounted } from 'vue'

export function useCountdown(initialSeconds = 60) {
  const countdown = ref(0)
  let timer: number | null = null
  
  const startCountdown = () => {
    // 清除可能存在的定时器
    if (timer) {
      clearInterval(timer)
    }
    
    // 设置初始倒计时
    countdown.value = initialSeconds
    
    // 启动定时器
    timer = window.setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--
      } else {
        stopCountdown()
      }
    }, 1000)
  }
  
  const stopCountdown = () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    countdown.value = 0
  }
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    if (timer) {
      clearInterval(timer)
    }
  })
  
  return {
    countdown,
    startCountdown,
    stopCountdown
  }
}
